<?php

/**
 * ship.php
 *
 * Author: netman
 * DateTime:  2023/10/18 14:45
 */
class Service_Api_Ship extends Contract_Api_Product
{
    use Trait_Api_Ship;
    use Trait_Api_Common;

    /**
     * 类型ID
     */
    const TYPE_ID = 104;
    /**
     * @var Service_Api_Fenxiao
     */
    private $fenxiao_service = null;

    public function __construct()
    {
        $this->fenxiao_service = new Service_Api_Fenxiao();
    }

    /**
     * 产品搜索
     * @param  array  $params
     * @return array
     * User: netman
     * Date: 2023/9/11 17:47
     */
    function search(array $params = array()): array
    {
        $key       = $params['key'] ;//关键字
        $page      = $params['page'];//页码
        $pagesize = $params['pagesize'];//条数
        $page      = $page < 1 ? 1 : $page;
        $pagesize = empty($pagesize) ? 10 : $pagesize;
        $offset    = ($page - 1) * $pagesize;

        $model = DB::select('id', 'title', 'litpic')->from('ship')
            ->where('ishidden', '=', 0);
        if ($key) {
            $model->where('title', 'like', "%{$key}%");
        }
        $count = $model->execute()->count();
        $list  = $model->offset($offset)->limit($pagesize)->execute()
            ->as_array();

        if ($list) {
            foreach ($list as &$item) {
                $item['litpic'] = $this->img_url($item['litpic']);
                $price          = DB::query(Database::SELECT, "SELECT min(price) as price FROM `sline_ship_line_suit_price` WHERE `shipid` = {$item['id']} ORDER BY `price` ASC LIMIT 1")->execute();
                $item['price']  = $price[0]['price'];
                $item['lineid'] = DB::select()->from('ship_line')
                    ->where('shipid', '=', $item['id'])
                    ->limit(1)
                    ->execute()
                    ->get('id');
            }
        }
        return array(
            'list'  => $list,
            'total' => $count
        );

    }

    /**
     * 产品详情
     * @param  array  $params
     * @return array
     * @throws Kohana_Exception
     * User: netman
     * Date: 2023/9/11 16:39
     */
    function info(array $params = array()): array
    {
        $info = array();
        $line_id = $params['line_id'];
        $userid = $params['userid'] ?? 0;
        //组合数据
        $info            = DB::select('id','title','litpic','piclist','sellpoint','isstyle',
            'supplierlist','startcity','finaldestid','shipid','satisfyscore','jifenbook_id','jifentprice_id',
            'jieshao','linebefore','visacontent','bookcontent','payment','feeinclude','description','lineday','linenight')->from('ship_line')
            ->where('id', '=', $line_id)
            ->execute()
            ->current();
        if ($info) {
            $info['litpic'] = $this->img_url($info['litpic']);
            $piclist                     = explode(',', $info['piclist']);
            foreach ($piclist as &$item) {
                $pic  = explode('||', $item);
                $item = $this->img_url($pic[0]);
            }
            $info['piclist'] = !empty($piclist) ? $piclist : [];
        }
        //行程安排
        if ($info['isstyle'] == 2) {
            $jieshao = DB::select()->from('ship_line_jieshao')
                ->where('lineid', '=', $info['id'])
                ->execute()
                ->as_array();
            if ($jieshao) {
                foreach ($jieshao as &$jc) {
                    $jc['content'] = $this->content_add_domain($jc['content']);
                }
            }
        } else {
            $jieshao = $this->content_add_domain($info['jieshao']);
        }
        //内容说明
        $contents     = DB::select('columnname', 'chinesename', 'isopen')->from('ship_line_content')->order_by('displayorder', 'asc')->execute()->as_array();
        $extendFields = DB::select()->from('ship_line_extend_field')->where('productid', '=', $info['id'])->execute()->current();
        foreach ($contents as $k => &$con) {
            if($con['isopen'] == 1 && $con['columnname'] != 'tupian'){
                if($con['columnname'] == 'jieshao'){
                    $con['chinesename'] = '行程安排';
                    $con['is_array'] = $info['isstyle'] == 2 ? 1 : 0;
                    $con['content'] = $jieshao;
                }else{
                    $con['content'] = isset($info[$con['columnname']]) ? $this->content_add_domain($info[$con['columnname']]) : (isset($extendFields[$con['columnname']]) ? $this->content_add_domain($extendFields[$con['columnname']]) : '');
                }
                if (!$con['content']) unset($contents[$k]);
            }else{
                unset($contents[$k]);
            }
        }
        $info['content_arr'] = array_values($contents);
        //游客信息配置
        $info['cfg_plugin_ship_line_usetourer'] = Model_Sysconfig::get_configs(0, 'cfg_plugin_ship_line_usetourer', true);

        // 最低价
        $info['price'] = Model_Ship::get_mini_price($info['id']);
        //满意度
        $info['score'] = St_Functions::get_satisfy(self::TYPE_ID, $info['id'], $info['satisfyscore']);
        //会员等级
        $info['rank_name'] = Model_Member::member_rank($userid, array('return' => 'current'));
        // 积分抵现配置
        $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], self::TYPE_ID);
        $info['jifentprice_info'] = $this->filter_data(array('isopen', 'id', 'toplimit', 'jifentprice'), $jifenprice_info);
        // 预定送积分
        $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], self::TYPE_ID);
        $info['jifenbook_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifenbook_info);
        //积分评论
        $jifencomment_info         = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $info['jifencomment_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifencomment_info);
        //邮轮信息
        $ship_info = DB::select()->from('ship')
            ->where('id', '=', $info['shipid'])
            ->execute()
            ->current();
        $supplier = DB::select('suppliername')->from('supplier')
            ->where('id','=',$info['supplierlist'])
            ->execute()
            ->get('suppliername');
        $product['ship_name'] = $ship_info['title'];
        $info['supplier_name'] = $supplier;

        //几天几晚
        $info['night'] = $info['linenight'];
        $info['days'] = $info['lineday'];
        $product['days'] = $info['lineday'];
        $product['startcity_text'] = DB::select('kindname')->from('destinations')
            ->where('id', '=', $info['startcity'])
            ->execute()
            ->get('kindname');
        $product['startcity_text'] = !empty($product['startcity_text']) ? $product['startcity_text'] : '';
        $product['finaldest_text'] = DB::select('kindname')->from('destinations')
            ->where('id', '=', $info['finaldestid'])
            ->execute()
            ->get('kindname');
        $product['finaldest_text'] = !empty($product['finaldest_text']) ? $product['finaldest_text'] : '';
        $product['ship_start'] = $ship_info['start'];
        $product['ship_seatnum'] = $ship_info['seatnum'];
        $product['ship_floornum'] = $ship_info['floornum'];
        $product['ship_weight'] = $ship_info['weight'];
        $product['supplier'] = $supplier;
        $info['product'] = $product;
        $info['discount_min_price'] = Model_Api_V2_Discount::get_discount($userid, 104, $info['id'], $info['price']);
        //点评人数
        $info['comment_num'] = DB::select('id')->from('comment')
            ->where('articleid','=',$info['id'])
            ->where('isshow','=',1)
            ->execute()
            ->count();
        //产品编号
        $info['product_series'] = St_Product::product_series($info['id'], 104);

        //行程出发到达时刻
        $day                    = DB::select('start_time', 'end_time')
            ->from('ship_line_voyage')
            ->where('day', '>=', strtotime(date('Y-m-d')))
            ->where('lineid', '=', $info['id'])
            ->execute()
            ->current();
        $info['start_time']     = !empty($day['start_time']) ? $day['start_time'] : '';
        $info['end_time']       = !empty($day['end_time']) ? $day['end_time'] : '';
        $info['startcity_text'] = $product['startcity_text'];
        $info['finaldest_text'] = $product['finaldest_text'];

        return array('info'=>$info);
    }

    /**
     * 产品查询条件
     * @return array
     * User: netman
     * Date: 2023/9/11 17:48
     */
    function query_condition(): array
    {
        $list = DB::select('id','attrname')->from('ship_line_attr')
            ->where('pid','=',0)
            ->where('isopen','=',1)
            ->execute()
            ->as_array();

        if($list){
            foreach ($list as &$item){
                $item['child'] = DB::select('id','attrname')->from('ship_line_attr')
                    ->where('pid','=',$item['id'])
                    ->where('isopen','=',1)
                    ->execute()
                    ->as_array();
            }


        }
        $child[] = ['id' => 'recommend','attrname' => '特价'];
        $child[] = ['id' => 'hot','attrname' => '爆款'];
        $list[] = ['id' => 0,'attrname' => '特价爆款','child' => $child];

        return array(
            'list' => $list,
        );
    }

    /**
     * 创建订单
     * @param  array  $params
     * @return array
     * User: netman
     * Date: 2023/9/13 16:24
     */
    function create_order(array $params = array()): array
    {
        //会员信息
        $lineId    = $params['line_id'];//航线id
        $dateid    = $params['date'];//出发日期
        $linkMan   = $params['linkman'];//联系人姓名
        $linkTel   = $params['linktel'];//联系人电话
        $linkEmail = $params['linkemail'];//联系人邮箱
        $member_info = $params['member_info'];
        $needJifen = $params['needjifen'];
        $linkTel   = empty($linkTel) && !empty($member_info) ? $member_info['mobile'] : $linkTel;
        $linkEmail = empty($linkEmail) && !empty($member_info) ? $member_info['email'] : $linkEmail;
        //积分数

        $suit_id         = $params['suit_id'];
        $number          = $params['number'];
        $child_number    = $params['child_number'];
        $plus_number     = $params['plus_number'];
        $child_no_number = $params['child_no_number'];
        $baby_number     = $params['baby_number'];
        $parcel_number   = $params['parcel_number'];

        // 游客信息
        $tourist = $params['tourist'] ?? '';
        if ($tourist) {
            $tourist = json_decode($tourist, true);
        }
        //附加产品
        $additional = $params['additional'];
        if ($additional) {
            $additional = json_decode($additional, true);
        }
        //楼层
        $floor = $params['floor'];
        if ($floor) {
            $floor = json_decode($floor, true);
        }
        //订单备注
        $remark             = $params['remark'];
        $envelope_member_id = $params['envelope_member_id'] ?? 0;
        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $source = $params['source'];

        $memberId = $params['mid'];

        $dingjin    = 0;//定金
        $curtime    = time();
        $suit_arr   = array();
        $totalprice = 0;
        $date_info  = DB::select()->from('ship_line_voyage')->where('day', '=', strtotime($dateid))->execute()->current();

        $startdate = date('Y-m-d', $date_info['day']);
        $enddate   = date('Y-m-d',strtotime("+{$date_info['day_num']} day",strtotime($startdate)));

        $status = 1;

        $suit_info = Model_Ship_Line::get_suit_info($lineId, $suit_id, $dateid);

        $need_confirm = DB::select('need_confirm')->from('ship_line_suit')->where('id', '=', $suit_id)->execute()->get('need_confirm');
        //只要有一个待确定，则整个订单为待确定
        if ($need_confirm == '1') {
            $status = 0;
        }

        if($parcel_number > 0){
            $room_num = ceil((($number-$parcel_number) + $child_number + $plus_number + $child_no_number + $baby_number) / $suit_info['peoplenum']) + $parcel_number;
        }else{
            $room_num = ceil(($number + $child_number + $plus_number + $child_no_number + $baby_number) / $suit_info['peoplenum']);
        }
        $suit_info['dingnum'] = $room_num;
        $suit_info['peoplenum'] = ($number + $child_number + $plus_number + $child_no_number + $baby_number);
        $suit_info['number']    = (int)$suit_info['number'];
        $suit_info['usedate']   = $suit_info['day'];
        if ($suit_info['number'] != -1 && $suit_info['dingnum'] > $suit_info['number']) {
            throw new Exception("房间" . $suit_info['suitname'] . '库存不足!');
        }
        if ($number > 0) {
            $totalprice += $number * $suit_info['price'];
        }
        if ($child_number > 0) {
            $totalprice += $child_number * $suit_info['child_price'];
        }
        if ($plus_number > 0) {
            $totalprice += $plus_number * $suit_info['plus_price'];
        }
        if ($child_no_number > 0) {
            $totalprice += $child_no_number * $suit_info['child_no_price'];
        }
        if ($baby_number > 0) {
            $totalprice += $baby_number * $suit_info['baby_price'];
        }
        if ($parcel_number > 0) {
            $totalprice += $parcel_number * $suit_info['parcel_price'];
        }
        if ($additional) {
            foreach ($additional as $val) {
                $price      = DB::select()->from('ship_line_additional')
                    ->where('id', '=', $val['id'])
                    ->execute()
                    ->get('price');
                $totalprice += ($val['num'] * $price);
            }
        }
        $floor_arr = array();
        if ($floor) {
            foreach ($floor as $k => $val) {
                $floor_price      = DB::select()->from('ship_line_suit_floor_price')
                    ->where('id', '=', $val['id'])
                    ->execute()
                    ->current();
                $totalprice += ($val['num'] * $floor_price['price']);
                if ($val > 0) {
                    $item        = array(
                        'id'    => $val['id'],
                        'name'  => $floor_price['name'],
                        'price' => $floor_price['price'],
                        'num'   => $val['num'],
                    );
                    $floor_arr[] = $item;
                }
            }
        }


        $suit_arr[] = $suit_info;

        //航线
        $info = ORM::factory('ship_line', $lineId)->as_array();

        //积分抵现.
        $jifentprice = 0;
        $useJifen    = 0;
        if ($needJifen) {
            $jifentprice = Model_Jifen_Price::calculate_jifentprice($info['jifentprice_id'], self::TYPE_ID, $needJifen, $member_info);
            $useJifen    = empty($jifentprice) ? 0 : 1;
            $needJifen   = empty($jifentprice) ? 0 : $needJifen;
        }
        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $jifencomment      = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];

        $paytype = $status == 0 ? 3 : 1;
        //订单编号
        $ordersn = Product::get_ordersn(self::TYPE_ID);

        $arr = array(
            'ordersn'       => $ordersn,
            'webid'         => 0,
            'typeid'        => self::TYPE_ID,
            'productautoid' => $info['id'],
            'productaid'    => $info['aid'],
            'productname'   => $info['title'],
            'price'         => round($totalprice / $room_num, 2),
            'pay_price'     => $totalprice,
            'childprice'    => 0,
            'oldprice'      => 0,
            'usedate'       => $startdate,
            'dingnum'       => $room_num,
            'childnum'      => 0,
            'oldnum'        => 0,
            'linkman'       => $linkMan,
            'linktel'       => $linkTel,
            'linkemail'     => $linkEmail,
            'jifentprice'   => $jifentprice,
            'jifenbook'     => $info['jifenbook_id'],
            'jifencomment'  => $jifencomment,
            'addtime'       => $curtime,
            'memberid'      => $memberId,
            'dingjin'       => $dingjin,
            'paytype'       => $paytype,
            'suitid'        => '',
            'departdate'    => $enddate,
            'usejifen'      => $useJifen,
            'needjifen'     => $needJifen,
            'status'        => $status,
            'remark'        => $remark,
            'contract_id'   => $info['contract_id'],
            'source'        => $source,
        );

        //优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $memberId, $arr);
        }

        //添加订单
        $arr['child_list'] = $suit_arr;
        $res = Model_Api_V2_Order::add_order($arr, 'Model_Ship_Line', $suit_arr);
        if ($res['status']) {

            $orderInfo = Model_Member_Order::get_order_by_ordersn($ordersn);
            $people    = array();
            if ($number > 0) {
                $people[] = array('num' => $number, 'price' => $suit_info['price'], 'name' => '成人');
            }
            if ($child_number > 0) {
                $people[] = array('num' => $child_number, 'price' => $suit_info['child_price'], 'name' => '儿童占床');
            }
            if ($plus_number > 0) {
                $people[] = array('num' => $plus_number, 'price' => $suit_info['plus_price'], 'name' => '加床');
            }
            if ($child_no_number > 0) {
                $people[] = array('num' => $child_no_number, 'price' => $suit_info['child_no_price'], 'name' => '儿童不占床');
            }
            if ($baby_number > 0) {
                $people[] = array('num' => $baby_number, 'price' => $suit_info['baby_price'], 'name' => '婴儿');
            }
            if ($parcel_number > 0) {
                $people[] = array('num' => $parcel_number, 'price' => $suit_info['parcel_price'], 'name' => '包舱');
            }

            foreach ($suit_arr as $row) {
                $child_model             = ORM::factory('member_order_child');
                $child_model->pid        = $orderInfo['id'];
                $child_model->suitid     = $row['suitid'];
                $child_model->price      = $row['price'];
                $child_model->title      = $row['suitname'];
                $child_model->dingnum    = $row['dingnum'];
                $child_model->peoplenum  = $row['peoplenum'];
                $child_model->voyageid   = $row['voyageid'];
                $child_model->status     = $status;
                $child_model->addtime    = $curtime;
                $child_model->ordersn    = $this->get_sub_ordersn(self::TYPE_ID);
                $child_model->attachinfo = serialize($additional);
                $child_model->crowd      = serialize($people);
                $child_model->floor      = serialize($floor_arr);
                $child_model->save();
            }

            //添加红包
            if (St_Functions::is_normal_app_install('red_envelope') && $envelope_member_id && $memberId) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $ordersn, self::TYPE_ID, $memberId);
            }

            // 优惠券
            if (!empty($coupon_check)) {
                Model_Coupon::add_coupon_order($coupon_check['cid'], $ordersn, $coupon_check['order_total_price'], $coupon_check, $coupon_id);
            }

            $tour_arr = array();
            foreach ($tourist as $k => $val) {
                $t['name']     = Common::remove_xss($val['tourername']);
                $t['cardtype'] = Common::remove_xss($val['cardtype']);
                $t['cardno']   = Common::remove_xss($val['idcard']);
                $t['sex']      = Common::remove_xss($val['sex']);
                $t['mobile']   = Common::remove_xss($val['mobile']);
                $tour_arr[]    = $t;
            }
            Model_Member_Order::add_tourer_pc($orderInfo['id'], $tour_arr, $memberId);

            //订单结算信息表数据更新
            Model_Member_Order_Compute::update($orderInfo['ordersn']);

            // 订单创建完成事件
            Hook::trigger('order_created', $orderInfo);

            return array(
                'ordersn'     => $ordersn, //订单编号
                'id'          => $orderInfo['id'],
                'status'      => $orderInfo['status'],
                'typeid'      => $orderInfo['typeid'],
                'needConfirm' => $status == 0 ? 1 : 0//是否需要确认，1-需要，0-否
            );

        }
        else {
            throw new Exception($res['msg']);

        }

    }


}